import 'package:flutter/material.dart';

import '../application.dart';

class Toast {

  static Alignment getPosition(String align){
    switch (align) {
      case 'top':
        return Alignment(0.0,-0.7);
      case 'bottom':
        return Alignment(0.0,0.7);
      default:
        return Alignment.center;
    }
  }

  static void show(String message,
      {int duration = 2, String align = 'center', AlignmentGeometry alignment}) {
    OverlayEntry entry = OverlayEntry(builder: (context) {
      return ToastWidget(message, alignment: alignment==null?getPosition(align):alignment, duration: duration,);
    });

    Overlay.of(Application.getContext()).insert(entry);
    Future.delayed(Duration(seconds: duration ?? 2)).then((value) {
      // 移除层可以通过调用OverlayEntry的remove方法。
      entry.remove();
    });
  }
}

class ToastWidget extends StatefulWidget{
  final String message;
  final int duration;
  final Alignment alignment;

  const ToastWidget(this.message, {Key key, this.alignment, this.duration = 2}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ToastWidgetState();

}

class _ToastWidgetState extends State<ToastWidget> {

  static ValueNotifier<int> instanceCount = ValueNotifier(0);
  int instanceIndex = 0;

  Alignment alignment;
  bool isMarginTop=true;
  double opacity = 1;

  @override
  void initState() {
    super.initState();
    instanceCount.value ++ ;
    instanceCount.addListener(onCreateInstance);

    print(['init aligment',widget.alignment.y]);
    if(widget.alignment.y > 0) {
      alignment = Alignment.bottomCenter;
      isMarginTop = false;
    }else{
      alignment = Alignment.topCenter;
    }
    Future.delayed(Duration(milliseconds: 10),(){
      if(!mounted)return;
      setState(() {
        alignment = widget.alignment;
      });
    });

    Future.delayed(Duration(milliseconds: widget.duration*1000-300),(){
      if(!mounted)return;
      setState(() {
        opacity = 0;
      });
    });
  }

  @override
  void dispose() {
    instanceCount.removeListener(onCreateInstance);
    //instanceCount.value -- ;
    super.dispose();
  }

  onCreateInstance(){
    if(!mounted)return;
    //使用异步,防止触发时在initState中执行
    Future.delayed(Duration(milliseconds: 10),()
    {
      if(!mounted)return;
      setState(() {
        instanceIndex++;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    const aDuration = Duration(milliseconds: 300);

    return AnimatedAlign(
      duration: aDuration,
      curve: Curves.easeOut,
      alignment: alignment,
      child: FittedBox(
        child: AnimatedOpacity(
          opacity: opacity,
          duration: aDuration,
          child: AnimatedContainer(
            duration: aDuration,
            curve: Curves.easeOut,
            decoration: BoxDecoration(
              color: Color.fromRGBO(0, 0, 0, .5),
              shape: BoxShape.rectangle,
              borderRadius: BorderRadius.circular(5),
            ),
            margin: EdgeInsets.only(top: isMarginTop?instanceIndex * 50.0:0,bottom: isMarginTop?0:instanceIndex * 50.0),
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: Material(
                color: Colors.transparent,
                child: Text(
                  widget.message,
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}